﻿using FPSO.HMI.Controls;
using FPSO.HMI.Utils;
using FPSO.Models.Constant;
using FPSO.Models.Domain;
using FPSO.Models.ViewModel.Controls;
using FPSO.Services;
using FPSO.Services.Impl;
using FPSO.ViewModel.Controls;
using MySql.Data.MySqlClient;
using Opc.Ua;
using OpcUaHelper;
using SafeLoad.NControl;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Protocols.WSTrust;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml.Linq;

namespace FPSO.HMI.Views.Dialog
{
    /// <summary>
    /// LoginDialog.xaml 的交互逻辑
    /// </summary>
    public partial class UCPumpDialog : Window
    {
        private PumpViewModel viewModel;
		private List<OPCTag> opcTags = new List<OPCTag>();
		private DispatcherTimer taskPumpStatusTimer;
		public UCPumpDialog(string name,List<OPCTag> tags)
        {
            InitializeComponent();
            viewModel = new PumpViewModel(name);
            this.DataContext = viewModel;
			opcTags = tags;

			initValveData();
			SetPumpStatus();
			SetDeviceStatus();

			taskPumpStatusTimer = new DispatcherTimer();
			taskPumpStatusTimer.Interval = TimeSpan.FromSeconds(1);
			taskPumpStatusTimer.Tick += PumpUpdateTaskTimer_Tick;
			taskPumpStatusTimer.Start();
        }

        /// <summary>
        /// Debug 在这里根据viewModel.ValveName进行取值显示操作
        /// </summary>
        private void initValveData()
        {
			// 随机生成泵状态0：远程，1：本地手动，2：本地自动
			viewModel.PumpStatus = 1;
			try
			{
				foreach (OPCTag tag in opcTags)
				{
					string opcname = tag.OpcName;
					Int16 value = Convert.ToInt16(tag.OpcValue.Value);
					if (opcname.Contains("Feedback_press"))
					{
						viewModel.OpenPress = value;
					}
					else if (opcname.Contains("Cmd_Final_Press"))
					{
						viewModel.TarPress = value;
					}
					else if (opcname.Contains("Failure"))
					{
						if(value > 0)
							viewModel.RunningStatus = 2;
					}
					else if (opcname.Contains("FaultPressFeedBack"))
					{
						if (value > 0)
							viewModel.RunningStatus = 3;
					}
				}
			}
			catch (Exception ex)
			{
				CommUtil.AddSystemLog(0, 2, ex.Message);
			}
		}

		private void updatePumpData()
		{
			try
			{
				foreach (OPCTag tag in opcTags)
				{
					string opcname = tag.OpcName;
					if (opcname.Contains("Feedback_press"))
					{
						string opc_add = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, opcname);
						DataValue data = App.UaClient.ReadNode(opc_add);
						Int16 value = Convert.ToInt16(data.Value);
						viewModel.OpenPress = value;
					}
					else if (opcname.Contains("Failure"))
					{
						string opc_add = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, opcname);
						DataValue data = App.UaClient.ReadNode(opc_add);
						Int16 value = Convert.ToInt16(data.Value);
						if (value > 0)
							viewModel.RunningStatus = 2;
					}
					else if (opcname.Contains("FaultPressFeedBack"))
					{
						string opc_add = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, opcname);
						DataValue data = App.UaClient.ReadNode(opc_add);
						Int16 value = Convert.ToInt16(data.Value);
						viewModel.RunningStatus = 3;
					}
				}
			}
			catch (Exception ex)
			{
				CommUtil.AddSystemLog(0, 2, ex.Message);
			}
		}
		/// <summary>
		/// 设置阀门状态
		/// 0：远程，1：本地手动，2：本地自动
		/// </summary>
		private void SetPumpStatus()
        {
			vavleStatus0.Background = Get_Status_Color(false);
			vavleStatus1.Background = Get_Status_Color(false);
			vavleStatus2.Background = Get_Status_Color(false);
			if (viewModel.PumpStatus == 0)
			{
				vavleStatus0.Background = Get_Status_Color(true);
			}
			if (viewModel.PumpStatus == 1)
			{
				vavleStatus1.Background = Get_Status_Color(true);
			}
			if (viewModel.PumpStatus == 2)
			{
				vavleStatus2.Background = Get_Status_Color(true);
			}
		}

		/// <summary>
		/// 设置设备状态
		/// 0：运行，1：关闭，3：故障，4：压力反馈异常
		/// </summary>
		private void SetDeviceStatus()
        {
			deviceStatus0.Background = Get_Status_Color(false);
			deviceStatus1.Background = Get_Status_Color(false);
			deviceStatus2.Background = Get_Status_Color(false);
			deviceStatus3.Background = Get_Status_Color(false);
			if (viewModel.RunningStatus == 0)
			{
				deviceStatus0.Background = Get_Status_Color(true);
			}
			if (viewModel.RunningStatus == 1)
			{
				deviceStatus1.Background = Get_Status_Color(true);
			}
			if (viewModel.RunningStatus == 2)
			{
				deviceStatus2.Background = Get_Status_Color(true);
			}
			if (viewModel.RunningStatus == 3)
			{
				deviceStatus3.Background = Get_Status_Color(true);
			}
		}

		private void PumpUpdateTaskTimer_Tick(object sender, EventArgs e)
		{
			updatePumpData();
		}

		/// <summary>
		/// 退出事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
			//返回false以阻止后续流程并退出 
			taskPumpStatusTimer.Stop();
			this.DialogResult = false;
        }

        /// <summary>
        /// 窗口拖动事件
        /// </summary>
        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                DragMove();
            }
        }

        /// <summary>
        /// 阀门打开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PumpOpen_Click(object sender, RoutedEventArgs e)
		{
			//输入泵的压力值后点击开启则下发泵操作动作
			if (viewModel.PumpStatus == 1 || viewModel.PumpStatus == 2)
			{
				foreach (OPCTag tag in opcTags)
				{
					string tagname = tag.OpcName;
					if (tagname.Contains("Cmd_Final_Press"))
					{
						string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
						//再次确认
						var dialgoResult = MessageBox.Show("确认修改信号下发?", "提示", MessageBoxButton.YesNo);
						if (dialgoResult == MessageBoxResult.Yes)
						{
							viewModel.OpenPress = Convert.ToInt32(OpenPreTxt.Text);
							try
							{
								Open_Btn.Background = Get_Status_Color(false);
								//[实船调试] 实船泵压力下发数据类型可能是Int16或者Int32
								//App.UaClient.WriteNode<Int32>(cmd_tag1, viewModel.OpenPress);
								App.UaClient.WriteNode<Int16>(cmd_tag1, Convert.ToInt16(viewModel.OpenPress));
							}
							catch (Exception ex)
							{
								CommUtil.AddSystemLog(0, 1, ex.Message);
							}
						}
						return;
					}
				}
			}
		}
		private void OpenPreTxt_LostFocus(object sender, RoutedEventArgs e)
		{

		}

		/// <summary>
		/// 获取状态颜色
		/// </summary>
		/// <param name="status"></param>
		/// <returns></returns>
		private SolidColorBrush Get_Status_Color(bool status)
        {
            return status
                ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#50d000"))
                : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#c6e0b6"));
        }
	}
}
